<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Swiper extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('swiper.index');
    }

    public function getSwiper() {
        $swipers = DB::table('swiper')->paginate(6)->toArray();
        return response()->json([
            'code'=>0, 
            'count'=>$swipers['total'],
            'data'=>$swipers['data']
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('swiper.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->only('title', 'url', 'swiper_sort', 'img_url');
        $res = DB::table('swiper')->insert($data);
        if ($res) {
            return returnStatus('success', '添加成功');
        } else {
            return returnStatus('fail', '添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $swiper = DB::table('swiper')->where('id', $id)->first();
        return view('swiper.edit', ['swiper'=>$swiper]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->only('title', 'url', 'swiper_sort', 'img_url');
        $res = DB::table('swiper')->where('id', $id)->update($data);
        if ($res) {
            return returnStatus('success', '修改成功');
        } else {
            return returnStatus('fail', '修改失败');
        }
         
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $res = DB::table('swiper')->where('id', $id)->delete();

        if ($res) {
            return returnStatus('success', '删除成功');
        } else {
            return returnStatus('fail', '删除失败');
        }
    }

    public function upload(Request $request) {
        $file = $request->file('file');
        return response()->json(uploadImg($file, 'swiper'));
    }
}
